package com.dingzhen.msg.mapper.impl;

import com.dingzhen.entity.Msg;
import com.dingzhen.msg.mapper.MsgMapper;
import com.dingzhen.support.ElasticsearchRestTemplate;
import com.dingzhen.utils.JacksonUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

@Repository
public class MsgMapperImpl implements MsgMapper {
    private final ElasticsearchRestTemplate elasticsearchRestTemplate;
    private final RestHighLevelClient restHighLevelClient;
    private final static String INDEX_MSG = "dingzhen01";
    public MsgMapperImpl(ElasticsearchRestTemplate elasticsearchRestTemplate, RestHighLevelClient restHighLevelClient) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
        this.restHighLevelClient = restHighLevelClient;
    }

    @Override
    public void addMsg(Msg msg) {
        elasticsearchRestTemplate.saveOrUpdate(msg.getId(), JacksonUtils.objectToString(msg), INDEX_MSG);
    }

    @Override
    public List<Msg> queryUserMsgByParam(Msg msg) {
        SearchSourceBuilder builder = SearchSourceBuilder.searchSource();
        builder.query(boolQuery()
                .must(termQuery("userMsgId", msg.getUserMsgId()))
        );

        List<Msg> msgList = elasticsearchRestTemplate.queryForList(builder, INDEX_MSG, Msg.class);
        return msgList;
    }


}
